// 历史记录管理工具
const ConfigManager = require('../config/config-manager.js');
const ApiConfig = ConfigManager.getApiConfig();

/**
 * 历史记录管理器
 */
class HistoryManager {
  constructor() {
    this.config = ApiConfig.history;
  }

  /**
   * 保存扫码记录
   * @param {string} content - 扫码内容
   * @param {Object} extraData - 额外数据
   */
  saveScanRecord(content, extraData = {}) {
    try {
      const history = this.getHistory(this.config.storageKeys.scanHistory);
      
      const newRecord = {
        id: Date.now().toString(),
        content: content,
        scanTime: Date.now(),
        timestamp: Date.now(), // 兼容字段
        type: this.config.recordTypes.scan,
        ...extraData
      };
      
      this.addToHistory(history, newRecord, this.config.storageKeys.scanHistory);
      return true;
    } catch (error) {
      console.error('保存扫描记录失败:', error);
      return false;
    }
  }

  /**
   * 保存二维码生成记录
   * @param {Object} data - 生成数据
   */
  saveQRGenerateRecord(data) {
    try {
      const history = this.getHistory(this.config.storageKeys.scanHistory);
      
      const newRecord = {
        id: Date.now(),
        content: data.content,
        type: data.codeType || (data.type === 'standard' || data.type === 'micro' ? 'qr' : 'barcode'),
        subType: data.type || data.barcodeType,
        time: new Date().toLocaleString(),
        isGenerated: true,
        batchMode: data.batchMode || false,
        barcodes: data.barcodes || [],
        recordType: this.config.recordTypes.qrGenerate
      };
      
      this.addToHistory(history, newRecord, this.config.storageKeys.scanHistory);
      return true;
    } catch (error) {
      console.error('保存二维码生成记录失败:', error);
      return false;
    }
  }

  /**
   * 保存条形码生成记录
   * @param {Object} data - 生成数据
   */
  saveBarcodeRecord(data) {
    try {
      const history = this.getHistory(this.config.storageKeys.barcodeHistory);
      
      if (data.batchMode) {
        const lines = data.batchContent.split('\n').filter(line => line.trim());
        lines.forEach((content, index) => {
          const record = {
            id: `${data.timestamp}_${index}`,
            type: 'barcode',
            subType: data.barcodeType,
            content: content.trim(),
            foregroundColor: data.foregroundColor,
            backgroundColor: data.backgroundColor,
            width: data.barcodeWidth,
            createTime: data.timestamp + index,
            batch: true,
            batchIndex: index + 1,
            batchTotal: lines.length,
            recordType: this.config.recordTypes.barcodeGenerate
          };
          
          this.addToHistory(history, record, this.config.storageKeys.barcodeHistory, false);
        });
        
        // 批量模式最后统一保存和限制
        this.limitHistorySize(history);
        wx.setStorageSync(this.config.storageKeys.barcodeHistory, history);
      } else {
        const record = {
          id: data.timestamp.toString(),
          type: 'barcode',
          subType: data.barcodeType,
          content: data.inputContent,
          foregroundColor: data.foregroundColor,
          backgroundColor: data.backgroundColor,
          width: data.barcodeWidth,
          createTime: data.timestamp,
          batch: false,
          recordType: this.config.recordTypes.barcodeGenerate
        };
        
        this.addToHistory(history, record, this.config.storageKeys.barcodeHistory);
      }
      
      return true;
    } catch (error) {
      console.error('保存条形码记录失败:', error);
      return false;
    }
  }

  /**
   * 保存生成历史记录（通用）
   * @param {Object} params - 生成参数
   */
  saveGenerateHistory(params) {
    try {
      const history = this.getHistory(this.config.storageKeys.generateHistory);
      
      const historyItem = {
        id: Date.now(),
        time: new Date(),
        timestamp: Date.now(),
        recordType: this.config.recordTypes.qrGenerate,
        ...params
      };
      
      this.addToHistory(history, historyItem, this.config.storageKeys.generateHistory);
      return true;
    } catch (error) {
      console.error('保存生成历史失败:', error);
      return false;
    }
  }

  /**
   * 获取历史记录
   * @param {string} storageKey - 存储键名
   */
  getHistory(storageKey) {
    return wx.getStorageSync(storageKey) || [];
  }

  /**
   * 添加记录到历史中
   * @param {Array} history - 历史记录数组
   * @param {Object} newRecord - 新记录
   * @param {string} storageKey - 存储键名
   * @param {boolean} autoSave - 是否自动保存和限制大小
   */
  addToHistory(history, newRecord, storageKey, autoSave = true) {
    // 检查是否已存在相同内容，如果存在则先删除
    const existingIndex = history.findIndex(item => item.content === newRecord.content);
    if (existingIndex !== -1) {
      history.splice(existingIndex, 1);
    }
    
    // 添加到历史记录开头
    history.unshift(newRecord);
    
    if (autoSave) {
      // 限制历史记录数量
      this.limitHistorySize(history);
      
      // 保存到本地存储
      wx.setStorageSync(storageKey, history);
    }
  }

  /**
   * 限制历史记录大小
   * @param {Array} history - 历史记录数组
   */
  limitHistorySize(history) {
    if (history.length > this.config.maxRecords) {
      history.splice(this.config.maxRecords);
    }
  }

  /**
   * 清空指定类型的历史记录
   * @param {string} storageKey - 存储键名
   */
  clearHistory(storageKey) {
    try {
      wx.removeStorageSync(storageKey);
      return true;
    } catch (error) {
      console.error('清空历史记录失败:', error);
      return false;
    }
  }

  /**
   * 删除指定的历史记录项
   * @param {string} storageKey - 存储键名
   * @param {Array} idsToDelete - 要删除的记录ID数组
   */
  deleteHistoryItems(storageKey, idsToDelete) {
    try {
      const history = this.getHistory(storageKey);
      const filteredHistory = history.filter(item => !idsToDelete.includes(item.id));
      wx.setStorageSync(storageKey, filteredHistory);
      return true;
    } catch (error) {
      console.error('删除历史记录失败:', error);
      return false;
    }
  }

  /**
   * 获取历史记录统计信息
   */
  getHistoryStats() {
    try {
      const scanHistory = this.getHistory(this.config.storageKeys.scanHistory);
      const generateHistory = this.getHistory(this.config.storageKeys.generateHistory);
      const barcodeHistory = this.getHistory(this.config.storageKeys.barcodeHistory);
      
      return {
        scanCount: scanHistory.length,
        generateCount: generateHistory.length,
        barcodeCount: barcodeHistory.length,
        totalCount: scanHistory.length + generateHistory.length + barcodeHistory.length,
        maxRecords: this.config.maxRecords
      };
    } catch (error) {
      console.error('获取历史记录统计失败:', error);
      return {
        scanCount: 0,
        generateCount: 0,
        barcodeCount: 0,
        totalCount: 0,
        maxRecords: this.config.maxRecords
      };
    }
  }
}

// 创建单例实例
const historyManager = new HistoryManager();

module.exports = historyManager; 